﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using java.security;
using System.Security.Cryptography;
using javax.crypto;
using javax.crypto.spec;
using java.security.spec;

namespace Pdelvo.Minecraft.Network
{
    public static class Security
    {
        public static KeyPair GenerateRSAKeyPair()
        {
            KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
            keyGen.initialize(1024);
            return keyGen.genKeyPair();
        }

        public static PublicKey GenerateRSAPublicKey(byte[] key)
        {
            X509EncodedKeySpec localX509EncodedKeySpec = new X509EncodedKeySpec(key);
            KeyFactory localKeyFactory = KeyFactory.getInstance("RSA");
            return localKeyFactory.generatePublic(localX509EncodedKeySpec);
        }

        public static Key GenerateRS4Key()
        {
            KeyGenerator gen = KeyGenerator.getInstance("RC4");
            gen.init(128);
            return gen.generateKey();
        }
        public static Key GenerateHC256Key()
        {
            return new SecretKeySpec(new SecureRandom().generateSeed(32), "HC-256");
        }
        public static Key GenerateAes128Key()
        {
            return new SecretKeySpec(new SecureRandom().generateSeed(16), "AES-128");
        }
        public static Key GenerateRS4Key(byte[] key)
        {
            return new SecretKeySpec(key, "RC4");
        }
        public static Key GenerateHCKey(byte[] key)
        {
            return new SecretKeySpec(key, "HC-256");
        }
        public static Key GenerateAesKey(byte[] key)
        {
            return new SecretKeySpec(key, "AES-128");
        }
        
        public static byte[] RSADecrypt(byte[] data, Key key)
        {
            var c = Cipher.getInstance("RSA");
            c.init(Cipher.DECRYPT_MODE, key);
            return c.doFinal(data);
        }

        public static byte[] RSAEncrypt(byte[] data, Key key)
        {
            var c = Cipher.getInstance("RSA");
            c.init(Cipher.ENCRYPT_MODE, key);
            return c.doFinal(data);
        }

        public static byte[] ComputeHash(params byte[][] bytes)
        {
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            foreach (var item in bytes)
            {
                digest.update(item);
            }
            return digest.digest();
        }
    }
}
